<?php
// 显示所有错误（仅在开发环境使用）
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 设置响应头
header('Content-Type: application/json');

// 引入必要的文件
require_once 'includes/AdminAuth.php';
$auth = new AdminAuth();

// 验证管理员是否已登录
if (!$auth->isLoggedIn()) {
    echo json_encode([
        'success' => false,
        'message' => '未授权访问'
    ]);
    exit;
}

// 获取数据库连接
$db = Database::getInstance();

// 获取请求的动作
$action = isset($_GET['action']) ? $_GET['action'] : '';

// 处理请求
switch ($action) {
    case 'get_user_stats':
        // 获取过去30天的用户注册数据
        $dates = [];
        $counts = [];
        
        for ($i = 29; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-$i days"));
            $dates[] = $date;
            
            $startDate = $date . ' 00:00:00';
            $endDate = $date . ' 23:59:59';
            
            $count = $db->fetchColumn("
                SELECT COUNT(*) 
                FROM " . DB_PREFIX . "users 
                WHERE created_at BETWEEN ? AND ?",
                [$startDate, $endDate]
            );
            
            $counts[] = (int)$count;
        }
        
        echo json_encode([
            'success' => true,
            'dates' => $dates,
            'counts' => $counts
        ]);
        break;
        
    case 'get_game_stats':
        // 获取游戏活跃度统计
        $gameStats = $db->fetchAll("
            SELECT g.name, COUNT(*) as play_count
            FROM " . DB_PREFIX . "game_records gr
            JOIN " . DB_PREFIX . "games g ON gr.game_id = g.id
            GROUP BY g.id
            ORDER BY play_count DESC
            LIMIT 10
        ");
        
        $games = [];
        $counts = [];
        
        foreach ($gameStats as $stat) {
            $games[] = $stat['name'];
            $counts[] = (int)$stat['play_count'];
        }
        
        echo json_encode([
            'success' => true,
            'games' => $games,
            'counts' => $counts
        ]);
        break;
        
    case 'get_achievement_stats':
        // 获取成就解锁统计
        $achievementStats = $db->fetchAll("
            SELECT a.name, COUNT(*) as unlock_count
            FROM " . DB_PREFIX . "user_achievements ua
            JOIN " . DB_PREFIX . "achievements a ON ua.achievement_id = a.id
            GROUP BY a.id
            ORDER BY unlock_count DESC
            LIMIT 6
        ");
        
        $achievements = [];
        $counts = [];
        
        foreach ($achievementStats as $stat) {
            $achievements[] = $stat['name'];
            $counts[] = (int)$stat['unlock_count'];
        }
        
        echo json_encode([
            'success' => true,
            'achievements' => $achievements,
            'counts' => $counts
        ]);
        break;
        
    case 'get_age_group_stats':
        // 获取年龄段分布统计（基于游戏记录中的年龄段游戏）
        $ageGroupStats = $db->fetchAll("
            SELECT 
                CASE 
                    WHEN g.min_age >= 3 AND g.max_age <= 4 THEN '3-4岁'
                    WHEN g.min_age >= 5 AND g.max_age <= 6 THEN '5-6岁'
                    WHEN g.min_age >= 7 AND g.max_age <= 8 THEN '7-8岁'
                    ELSE '其他'
                END as age_group,
                COUNT(*) as play_count
            FROM " . DB_PREFIX . "game_records gr
            JOIN " . DB_PREFIX . "games g ON gr.game_id = g.id
            GROUP BY age_group
        ");
        
        $groups = [];
        $counts = [];
        
        foreach ($ageGroupStats as $stat) {
            $groups[] = $stat['age_group'];
            $counts[] = (int)$stat['play_count'];
        }
        
        echo json_encode([
            'success' => true,
            'groups' => $groups,
            'counts' => $counts
        ]);
        break;
        
    case 'get_recent_activity':
        // 获取最近的活动
        $recentActivity = $db->fetchAll("
            (SELECT 
                u.username, 
                'register' as activity_type, 
                NULL as related_name,
                u.created_at as activity_time
            FROM " . DB_PREFIX . "users u
            WHERE u.role = 'user'
            ORDER BY u.created_at DESC
            LIMIT 5)
            
            UNION ALL
            
            (SELECT 
                u.username, 
                'game_play' as activity_type,
                g.name as related_name,
                gr.played_at as activity_time
            FROM " . DB_PREFIX . "game_records gr
            JOIN " . DB_PREFIX . "users u ON gr.user_id = u.id
            JOIN " . DB_PREFIX . "games g ON gr.game_id = g.id
            ORDER BY gr.played_at DESC
            LIMIT 5)
            
            UNION ALL
            
            (SELECT 
                u.username, 
                'achievement' as activity_type,
                a.name as related_name,
                ua.unlocked_at as activity_time
            FROM " . DB_PREFIX . "user_achievements ua
            JOIN " . DB_PREFIX . "users u ON ua.user_id = u.id
            JOIN " . DB_PREFIX . "achievements a ON ua.achievement_id = a.id
            ORDER BY ua.unlocked_at DESC
            LIMIT 5)
            
            ORDER BY activity_time DESC
            LIMIT 10
        ");
        
        $activities = [];
        
        foreach ($recentActivity as $activity) {
            $description = '';
            switch ($activity['activity_type']) {
                case 'register':
                    $description = $activity['username'] . ' 注册了账号';
                    break;
                case 'game_play':
                    $description = $activity['username'] . ' 玩了游戏 ' . $activity['related_name'];
                    break;
                case 'achievement':
                    $description = $activity['username'] . ' 解锁了成就 ' . $activity['related_name'];
                    break;
            }
            
            $activities[] = [
                'description' => $description,
                'time' => date('Y-m-d H:i', strtotime($activity['activity_time'])),
                'type' => $activity['activity_type']
            ];
        }
        
        echo json_encode([
            'success' => true,
            'activities' => $activities
        ]);
        break;
        
    default:
        echo json_encode([
            'success' => false,
            'message' => '未知的操作'
        ]);
        break;
}
?> 